var express = require("express");
var router = express.Router();
var path = require("path");
var fs = require("fs");
var multer = require("multer");
var upload = multer({ dest: "./upload/audio" });
var { courseModel, chapterModel } = require("../model/model");
var multiparty = require("multiparty");

// 读取文件
const  loadFileHashes = ()=>{
  try{
    const data = fs.readFileSync('fileHashes.json','utf8')
    return JSON.parse(data)
  }catch(err){
    return {}
  }
}

// 写入文件
const saveFileHashes = (fileHashes) => {
  const data = JSON.stringify(fileHashes, null, 2);
  fs.writeFileSync('fileHashes.json', data, 'utf8');
};

let fileHashes = loadFileHashes();
// 图片上传
router.post("/img", (req, res) => {
  let form = new multiparty.Form();
  form.uploadDir = "upload";
  form.parse(req, (err, formDate, imgDate) => {
    console.log(imgDate.imageFile[0].path);
    res.send({
      code: 200,
      data: "http://127.0.0.1:3000/" + imgDate.imageFile[0].path,
    });
  });
});
// 视频上传
router.post("/video", upload.single("file"), (req, res) => {
  const file = req.file; // 获取文件对象
  const totalChunks = parseInt(req.body.totalChunks); // 获取总块数
  const filename = req.body.filename; // 获取文件名
  const currentChunk = parseInt(req.body.currentChunk);
  const chunkPath = path.join(
    "upload/audio",
    `${filename}-chunk-${currentChunk}`
  );
  const chunkStream = fs.createReadStream(file.path);
  const writeStream = fs.createWriteStream(chunkPath);
  chunkStream.pipe(writeStream);
  chunkStream.on("end", () => {
    fs.unlinkSync(file.path);
    const progress = ((currentChunk + 1) / totalChunks) * 100;
    res.json({ progress });
  });
});
// 分片合并
router.post("/merge", (req, res) => {
  const filename = req.body.filename; // 获取文件名
  const totalChunks = parseInt(req.body.totalChunks); // 获取总块数
  const fileHash = req.body.fileHash;
  const mergedPath = path.join("upload/audio", filename); //生成合并文件存储位置
  const writeStream = fs.createWriteStream(mergedPath); // 创建写入合并文件可写流
  const mergeChunks = (index) => {
    if (index === totalChunks) {
      writeStream.end(); // 关闭写入流
      fileHashes[fileHash] = [true, "http://127.0.0.1:3000/" + mergedPath];
      saveFileHashes(fileHashes); // 将fileHashes对象的内容写入到文件中
      res.send({
        code: 200,
        path: "http://127.0.0.1:3000/" + mergedPath
      }); //响应合并成功文件
      return;
    }
    const chunkPath = path.join("upload/audio", `${filename}-chunk-${index}`);
    const readStream = fs.createReadStream(chunkPath);
    readStream.on('end', () => {
      fs.unlinkSync(chunkPath); // 删除已经合并的块文件
      mergeChunks(index + 1); //递归合并下一块
    });
    readStream.pipe(writeStream, { end: false });
  };

  mergeChunks(0);
});
// 秒传
router.post('/check-file',(req,res)=>{
  const fileHash = req.body.fileHash
  if(fileHashes[fileHash][0]){
    res.send({
      code:200,
      path : fileHashes[fileHash][1]
    })
  }else{
    res.sendStatus(404)
  }
})

// 服务器关闭时保存fileHashes对象到文件里
process.on('SIGINT', () => {
  saveFileHashes(fileHashes);
  process.exit();
});

router.post('/course', async (req, res) => {
  try {
    const { courseObj, chaptArray } = req.body;
    
    const course = new courseModel(courseObj);
  
    const chapters = await Promise.all(chaptArray.map(chaptObj => new chapterModel(chaptObj).save()));
    
    course.chapters = chapters.map(chapter => chapter._id);
    await course.save();
  
    res.send({ code: 200 });
  } catch (error) {
    res.status(500).send({ error: "Internal server error" });
  }
});



module.exports = router;
